#include "kt404a.h"


CKT404A::CKT404A()
{
  m_serlPtr = NULL;
}

CKT404A::~CKT404A()
{
}

void CKT404A::Init(HardwareSerial *serl)
{
  m_serlPtr = serl;
}

void CKT404A::SetVoice(uint8_t vol)
{
  flushRcvBuffer();

  uint8_t cmd[] = {0x7E, 0xFF, 0x06, 0x06, 0x00, 0x00, vol, 0x00, 0x00, 0xEF};
  checksum(KT404_CMD_LEN, cmd);
  writeCmd(KT404_CMD_LEN, cmd);
}

void CKT404A::AddVoice()
{
  flushRcvBuffer();

  uint8_t cmd[] = {0x7E, 0xFF, 0x06, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEF};
  checksum(KT404_CMD_LEN, cmd);
  writeCmd(KT404_CMD_LEN, cmd);
}

void CKT404A::DecVoice()
{
  flushRcvBuffer();

  uint8_t cmd[] = {0x7E, 0xFF, 0x06, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEF};
  checksum(KT404_CMD_LEN, cmd);
  writeCmd(KT404_CMD_LEN, cmd);
}

void CKT404A::Play(uint16_t idx)
{
  flushRcvBuffer();

  uint8_t high = (idx >> 8) & 0xFF;
  uint8_t low = idx & 0xFF;
  uint8_t cmd[] = {0x7E, 0xFF, 0x06, 0x03, 0x00, high, low, 0x00, 0x00, 0xEF};
  checksum(KT404_CMD_LEN, cmd);
  writeCmd(KT404_CMD_LEN, cmd);
}

void CKT404A::Play(uint8_t dir, uint8_t idx)
{
  flushRcvBuffer();

  uint8_t cmd[] = {0x7E, 0xFF, 0x06, 0x0F, 0x00, dir, idx, 0x00, 0x00, 0xEF};
  checksum(KT404_CMD_LEN, cmd);
  writeCmd(KT404_CMD_LEN, cmd);
}

void CKT404A::Stop()
{
  flushRcvBuffer();

  uint8_t cmd[] = {0x7E, 0xFF, 0x06, 0x16, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEF};
  checksum(KT404_CMD_LEN, cmd);
  writeCmd(KT404_CMD_LEN, cmd);
}

void CKT404A::Pause()
{
  flushRcvBuffer();

  uint8_t cmd[] = {0x7E, 0xFF, 0x06, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEF};
  checksum(KT404_CMD_LEN, cmd);
  writeCmd(KT404_CMD_LEN, cmd);
}

void CKT404A::Resume()
{
  flushRcvBuffer();

  uint8_t cmd[] = {0x7E, 0xFF, 0x06, 0x0D, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEF};
  checksum(KT404_CMD_LEN, cmd);
  writeCmd(KT404_CMD_LEN, cmd);
}

void CKT404A::flushRcvBuffer()
{
  while (m_serlPtr->available() > 0) {
    m_serlPtr->read();
  }
}

void CKT404A::checksum(uint8_t len, uint8_t *cmd)
{
  uint16_t sum = 0;
  for (uint8_t i = 1;i < (len - 3);i++) {
    sum += cmd[i];
  }
  sum=((0xFFFF - sum) + 1);
  cmd[len-3] = (sum>>8) & 0xFF;
  cmd[len-2] = sum & 0xFF;
}

void CKT404A::writeCmd(uint8_t len, uint8_t *cmd)
{
  m_serlPtr->write(cmd, len);
  m_serlPtr->flush();
  delay(20);
}





  